#! /usr/bin/env bash

cd "$(dirname "$0")"
cd ..

echo $(date +"%Y-%m-%d %H:%M:%S") Generating authentication list
network=$(ls -1 capture/????????????-*/key.txt 2> /dev/null)
while read key
do
	if [ -n "$key" ]
	then
		identifier=${key:8:-8}
		bssid=$(echo ${identifier:0:12} | tr '[a-z]' '[A-Z]' | sed 's/\(..\)/&:/g;s/:$//')
	
		if [ -f capture/$identifier/essid.txt ]
		then
			essid=$(cat capture/$identifier/essid.txt)
		else
			essid=
			log=$(ls -1 capture/$identifier | grep --perl-regex "^[0-9]{4}(?:-[0-9]{2}){6}\.csv$")
			while read file
			do
				if [ -n "$file" ]
				then
					line=$(cat capture/$identifier/$file | head --lines 3 | tail --lines 1)
					essid=$(echo $line | cut -d ',' -f 14)
					essid=${essid:1}
					if [ ! -z "$essid" ]
					then
						echo $essid > capture/$identifier/essid.txt
						break
					fi
				fi
			done <<< "$log" 
		fi

		if [ -n "$essid" ]
		then
			echo $bssid \"$essid\" \"$(cat $key)\"
		fi
	fi
done <<< "$network" >> database/key.txt

echo $(date +"%Y-%m-%d %H:%M:%S") Generating mobile configuration
php -f script/mobileconfig.php database/key.txt database/key-essid.txt > database/key.mobileconfig

